/*
Author: Praveen Kambam Sugavanam
Last Updated: 04/15/2012 02:34
*/

#include <Kernel.h>
#include <SuperBlock.h>
#include <IndexNode.h>
#include <DirectoryEntry.h>
#include <stdlib.h>
#include <stdio.h>
#include <FileSystem.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/* find command */
void find(String n);
int main(int argc, char **argv)
{
  Kernel::initialize();

  if (argc != 2)
  {
    fprintf (stderr, "usage: find <dirname> \n");
  }
  find(argv[1]);
  Kernel::Exit(0);
}
void find(String n)
{
  //String n = "/";
  int fd = Kernel::open(n,0);
  if(fd < 0)
    {
      // process->errno = ???
      return ;
    }

  // create a buffer for reading directory entries
  DirectoryEntry *directoryEntry = new DirectoryEntry();

  int status = 0;
  int close_status;
  short indexNodeNumber = -1;
  // while there are more directory blocks to be read
  while(true)
    {
      // read a directory entry

      status = Kernel::readdir(fd, directoryEntry);
          //  printf("Inside while 2\n");
      if(status <= 0)
      {
        // we got to the end of the directory, or 
        // encountered an error, so quit
        break;
      }
      // printf("Inode of the de : %d \n",directoryEntry->getIno());
  

       /* Stat *stat = new Stat();
      status = Kernel::stat(n, stat);
      if(status < 0)
	{
	 // Kernel::perror(PROGRAM_NAME);
	  Kernel::Exit(1);
	}
      // mask the file type from the mode
      short type = (short)(stat->getMode() &((short)0170000));*/
       
       if(strcmp(directoryEntry->getName(),".")&& strcmp(directoryEntry->getName(),".."))
         {
           if (strcmp("/",n))
             printf("%s",n);  
           printf("/%s \n",directoryEntry->getName());
         }
       if(strcmp(directoryEntry->getName(),".")&& strcmp(directoryEntry->getName(),".."))
	{
	//append the name to this name and call this recursively.
	char* appName = (char*)malloc(strlen(n) + strlen(directoryEntry->getName()) + 2);
	strcpy(appName, n);
	if (strcmp("/",n))
          strcat(appName, "/");

        strcat(appName, directoryEntry->getName());
        //printf("In here and %s\n",appName);
        find(appName);
	}
	
    }

  
}
